from django.http import HttpResponse
import uuid
import json
import copy
from src.components.mongodb_handler import MongodbHandler as MongodbHandler
from src.components.redis_handler import RedisHandler as RedisHandler
from src.model.response import Response as Response
from src.constant.http_status import HttpStatus as HttpStatus


def auth(request):
    """
    code2Session接口
    :param request:
    :return:
    """
    # 小程序 appId
    appid = '111'
    # 小程序 appSecret
    secret = '222'
    # 登录时获取的 code
    js_code = json.loads(str(request.body, encoding="utf-8"))['code']
    # 授权类型，此处只需填写 authorization_code
    grant_type = 'authorization_code'
    # 接口url
    url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid + '&secret=' + secret + '&js_code=' + js_code \
          + '&grant_type=' + grant_type

    # 由于小程序还没有注册完，因此此处暂时先写死
    # response_data = requests.get(url)
    response_data = {
        'openid': '222',
        'session_key': 'bbb',
        'unionid': 'ccc',
        'errcode': 0,
        'errmsg': 'ddd'
    }
    print(response_data)

    # 连接数据库
    database = MongodbHandler.get_db('localhost', 27017, 'black-widow')

    # 获取user集合
    user_collection = database.user
    # 查找符合条件的记录，返回的是Cursor类型的对象
    find_result_cursor = user_collection.find({
        'openid': response_data['openid']
    })
    # 如果没有这个用户则插入记录，如果有这个用户则修改login属性
    user_id = None
    if find_result_cursor is not None and find_result_cursor.count() > 0:
        for record in find_result_cursor:
            user_id = record['_id']
            user_collection.update_one({'_id': record['_id']}, {'$set': {'login': 1}})
    else:
        # 深层拷贝，否则entity和response指向同一个对象
        user_dict = copy.deepcopy(response_data)
        user_dict['login'] = 1
        user_dict.pop('errcode')
        user_dict.pop('errmsg')
        result = user_collection.insert_one(user_dict)
        user_id = result.inserted_id
    response_data['userId'] = str(user_id)

    # 获取rel_user_stock_info集合
    rel_user_stock_info_collection = database.rel_user_stock_info
    # 查找当前登录用户已经订阅的股票的code集合
    find_result_cursor = rel_user_stock_info_collection.find({
        'user_id': user_id
    })
    if find_result_cursor is not None and find_result_cursor.count() > 0:
        stock_code_list = list()
        for record in find_result_cursor:
            stock_code = str(record['code'])
            stock_code_list.append(stock_code)
        response_data['stockCodeList'] = stock_code_list

    # 生成token，并存储在response中
    token = str(uuid.uuid4())
    response_data['token'] = token

    # 连接redis，以user_id为key，token为value，存储键值对。使用默认的过期时间
    RedisHandler.create_client()
    RedisHandler.set_with_default_expire_time(str(user_id), token)
    RedisHandler.close()

    response = Response(True, HttpStatus.OK, response_data, '认证成功')
    return response


def set_session(request):
    """
    测试方法
    保存session数据
    :param request:
    :return:
    """
    request.session['username'] = 'Django'
    request.session['verify_code'] = '123456'
    return HttpResponse('保存session数据成功')


def get_session(request):
    """
    测试方法
    获取session数据
    :param request:
    :return:
    """
    username = request.session.get('username')
    verify_code = request.session.get('verify_code')
    text = 'username=%s, verify_code=%s' % (username, verify_code)
    return HttpResponse(text)
